package com.example.demo.util.credentials;


import java.util.concurrent.atomic.AtomicInteger;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;

/**
 * 现在此类没有被使用，在UserRealmTest使用的是encrypt中的同名类(缓存的配置文件的路径错误,在这个类中已更改)
 * </p>
 * 第11章使用的是此类
 * @author Henry.Y 
 * @date 2019-05-24
 */
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher{

	private Ehcache passwordRetryCache;
	
	public RetryLimitHashedCredentialsMatcher(){
		//CacheManager cacheManager= CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("ehcache.xml"));
		CacheManager cacheManager= CacheManager.newInstance(CacheManager.class.getClassLoader().getResource("configuration/password-ehcache.xml"));   //第11章时使用
		passwordRetryCache=cacheManager.getCache("passwordRetryCache");
	}
	
    public boolean doCredentialsMatch(AuthenticationToken token,AuthenticationInfo info){
    	String username= (String)token.getPrincipal();
    	Element element= passwordRetryCache.get("passwordRetryCache");
    	if(null==element){
    		element= new Element(username, new AtomicInteger(0));
    		passwordRetryCache.put(element);
    	}
    	AtomicInteger retryCount= (AtomicInteger)element.getObjectValue();
    	if(retryCount.incrementAndGet()>5){
    		throw new ExcessiveAttemptsException();
    	}
    	boolean matcher= super.doCredentialsMatch(token, info);
    	if(matcher){
    		passwordRetryCache.remove(username);
    	}
    	return matcher;
    }
}
